#include <iostream>
#include <unordered_map>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "../Sock/Logmessage.hpp"
#include "../Sock/errno.hpp"

class User
{
    std::string ip_;
    uint16_t    port_;
    int sock_;
public:    
    User(const std::string& ip,const uint16_t port,int sock)
        :ip_(ip),port_(port),sock_(sock)
    {}
    const std::string getIp() const {return ip_;}
    const uint16_t getPort()const {return port_;}
    const int getSock(){return sock_;}
};


class onlineUser
{
    std::unordered_map<std::string,User> Users;
public:
    void addUser(const std::string& ip,const uint16_t port,int sock)
    {
        std::string key=ip+"/"+std::to_string(port);
        Users.insert(make_pair(key,User(ip,port,sock)));
        logMessage(NORMAL,"ADDUser success...");
    }    
    void delUser(const std::string& ip,const uint16_t port)
    {
        std::string key=ip+"/"+std::to_string(port);
        Users.erase(key);
    }    
    //用户是否在线
    bool isOnline(const std::string& ip,const uint16_t port)
    {
        std::string key=ip+"/"+std::to_string(port);
        return Users.find(key) !=Users.end();
    }    

    //消息路由
    void messageRouting(std::string& ip,uint16_t port,std::string& msg)
    {
        for (auto& user:Users)
        {
            //构建转发消息
            std::string resMsg=ip+"/"+std::to_string(port)+" # ";
            resMsg+=msg;
            //给每一个客户端连接发送消息
            send(user.second.getSock(),resMsg.c_str(),resMsg.size(),0);
        }
        logMessage(NORMAL,"messageRouting success...,Forwarded a total of %dmessages",Users.size());
        
    }


};